#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
浏览器自动化脚本 - 模拟点击页面按钮
使用Selenium WebDriver控制Edge浏览器
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import sys
import random
from datetime import datetime
import os

class BrowserAutomation:
    def __init__(self):
        """初始化浏览器自动化类"""
        self.driver = None
        self.wait = None
        
    def setup_driver(self):
        """设置Edge浏览器驱动"""
        try:
            # Edge浏览器选项
            edge_options = Options()
            # 可选：无头模式（不显示浏览器窗口）
            # edge_options.add_argument('--headless')
            
            # 设置用户代理
            edge_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59')
            
            # 禁用一些可能影响自动化的功能
            edge_options.add_argument('--disable-blink-features=AutomationControlled')
            edge_options.add_experimental_option("excludeSwitches", ["enable-automation"])
            edge_options.add_experimental_option('useAutomationExtension', False)
            
            # 创建WebDriver实例
            self.driver = webdriver.Edge(options=edge_options)
            
            # 设置隐式等待
            self.driver.implicitly_wait(10)
            
            # 创建显式等待对象
            self.wait = WebDriverWait(self.driver, 20)
            
            # 执行JavaScript来隐藏webdriver特征
            self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            
            print("✓ Edge浏览器驱动初始化成功")
            return True
            
        except Exception as e:
            print(f"✗ 浏览器驱动初始化失败: {e}")
            return False
    
    def connect_to_existing_browser(self):
        """连接到已存在的浏览器实例"""
        try:
            # 尝试连接到现有的Edge浏览器
            # 注意：这需要Edge浏览器以调试模式启动
            print("=" * 60)
            print("正在尝试连接到现有浏览器...")
            print("连接地址: 127.0.0.1:9222")
            print("-" * 60)
            print("⚠️ 如果连接失败，请确保Edge浏览器以调试模式启动：")
            print("命令: msedge.exe --remote-debugging-port=9222 --user-data-dir=C:\\temp\\edge_debug")
            print("=" * 60)
            
            # 连接到调试端口
            edge_options = Options()
            edge_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
            
            print("尝试建立连接...")
            self.driver = webdriver.Edge(options=edge_options)
            self.driver.implicitly_wait(10)
            self.wait = WebDriverWait(self.driver, 20)
            
            # 验证连接
            current_url = self.driver.current_url
            print("=" * 60)
            print("✅ 成功连接到现有浏览器！")
            print(f"当前页面: {current_url}")
            print("=" * 60)
            return True
            
        except Exception as e:
            print("=" * 60)
            print(f"❌ 连接现有浏览器失败！")
            print(f"错误信息: {e}")
            print("-" * 60)
            print("可能的原因:")
            print("1. Edge浏览器没有以调试模式启动")
            print("2. 调试端口不是9222")
            print("3. 端口被其他程序占用")
            print("=" * 60)
            return False
    
    def highlight_element(self, element, duration=2):
        """高亮显示元素"""
        try:
            # 保存原始样式
            original_style = element.get_attribute("style")
            
            # 高亮效果
            self.driver.execute_script("""
                arguments[0].style.border = '3px solid red';
                arguments[0].style.backgroundColor = 'yellow';
                arguments[0].style.boxShadow = '0 0 10px red';
            """, element)
            
            print(f"🔍 高亮显示元素 {duration} 秒...")
            time.sleep(duration)
            
            # 恢复原始样式
            self.driver.execute_script("arguments[0].style = arguments[1];", element, original_style)
            
        except Exception as e:
            print(f"高亮显示失败: {e}")
    
    def simulate_human_mouse_movement(self, element):
        """模拟人类鼠标移动"""
        try:
            # 获取元素位置
            location = element.location
            size = element.size
            
            # 计算元素中心点
            center_x = location['x'] + size['width'] // 2
            center_y = location['y'] + size['height'] // 2
            
            # 创建ActionChains对象
            actions = ActionChains(self.driver)
            
            # 模拟人类移动路径：先移动到随机位置，再移动到目标
            start_x = random.randint(100, 500)
            start_y = random.randint(100, 400)
            
            print(f"🖱️  模拟鼠标移动: ({start_x}, {start_y}) -> ({center_x}, {center_y})")
            
            # 移动到起始位置
            actions.move_by_offset(start_x, start_y)
            time.sleep(0.5)
            
            # 移动到目标元素
            actions.move_to_element(element)
            time.sleep(0.3)
            
            # 执行移动
            actions.perform()
            
            print("✓ 鼠标移动完成")
            
        except Exception as e:
            print(f"鼠标移动失败: {e}")
    
    def simulate_human_click(self, element):
        """模拟人类点击行为"""
        try:
            actions = ActionChains(self.driver)
            
            # 移动到元素
            actions.move_to_element(element)
            time.sleep(0.2)
            
            # 模拟鼠标悬停
            actions.pause(0.3)
            
            # 点击
            actions.click()
            
            # 执行动作
            actions.perform()
            
            print("✓ 模拟人类点击完成")
            
        except Exception as e:
            print(f"模拟点击失败: {e}")
    
    def find_and_click_positioning_button(self):
        """查找并点击定位按钮"""
        try:
            print("正在查找定位按钮...")
            
            # 多种选择器策略来查找定位按钮
            selectors = [
                # 通过文本内容查找
                "//button[contains(., '定位')]",
                # 通过class和文本组合查找
                "//button[@class='ant-btn css-1wismvm ant-btn-default MultidateHead_btn__WPzra' and contains(., '定位')]",
                # 通过span内的文本查找
                "//button[.//span[text()='定位']]",
                # 通过SVG图标查找
                "//button[.//svg[contains(@href, '#icon-positioning')]]",
                # 通过父级class查找
                "//div[@class='MultidateHead_functionStyle__hYMLT']//button[contains(., '定位')]"
            ]
            
            button = None
            for selector in selectors:
                try:
                    button = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到定位按钮 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if button is None:
                print("✗ 未找到定位按钮")
                return False
            
            # 滚动到按钮位置
            self.driver.execute_script("arguments[0].scrollIntoView(true);", button)
            time.sleep(0.3)
            
            # 高亮显示按钮
            self.highlight_element(button, duration=0.2)
            
            # 模拟人类鼠标移动
            self.simulate_human_mouse_movement(button)
            
            # 再次高亮显示
            self.highlight_element(button, duration=0.5)
            
            # 模拟人类点击
            self.simulate_human_click(button)
            
            print("✓ 成功点击定位按钮")
            
            # 等待一下看是否有响应
            time.sleep(0.5)
            
            return True
            
        except Exception as e:
            print(f"✗ 点击定位按钮失败: {e}")
            return False
    
    def simulate_human_typing(self, element, text):
        """模拟人类打字行为"""
        try:
            # 清空输入框
            element.clear()
            time.sleep(0.2)
            
            # 点击输入框获得焦点
            element.click()
            time.sleep(0.3)
            
            # 逐字符输入，模拟人类打字速度
            for char in text:
                element.send_keys(char)
                # 随机延迟，模拟人类打字速度
                delay = random.uniform(0.01, 0.05)
                time.sleep(delay)
            
            print(f"✓ 模拟人类打字完成: {text}")
            
        except Exception as e:
            print(f"模拟打字失败: {e}")
    
    def find_and_input_text(self, text, placeholder="请输入地名地址"):
        """查找输入框并输入文本"""
        try:
            print(f"正在查找输入框并输入文本: {text}")
            
            # 多种选择器策略来查找输入框
            selectors = [
                f"//input[@placeholder='{placeholder}']",
                "//input[@class='ant-input css-1wismvm']",
                "//span[@class='ant-input-affix-wrapper css-1wismvm']//input",
                "//div[@class='MultidateHead_search__wvPW6']//input"
            ]
            
            input_element = None
            for selector in selectors:
                try:
                    input_element = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if input_element is None:
                print("✗ 未找到输入框")
                return False
            
            # 滚动到输入框位置
            self.driver.execute_script("arguments[0].scrollIntoView(true);", input_element)
            time.sleep(1)
            
            # 高亮显示输入框
            self.highlight_element(input_element, duration=0.5)
            
            # 模拟人类鼠标移动
            self.simulate_human_mouse_movement(input_element)
            
            # 模拟人类打字
            self.simulate_human_typing(input_element, text)
            
            print(f"✓ 成功输入文本: {text}")
            
            return True
            
        except Exception as e:
            print(f"✗ 输入文本失败: {e}")
            return False
    
    def handle_timeline(self):
        """处理时间轴点击"""
        try:
            print("正在查找时间轴...")
            
            # 等待时间轴加载
            time.sleep(2)
            
            # 查找时间轴的多种可能选择器
            timeline_selectors = [
                "//div[@id='time']",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]",
                "//div[contains(@class, 'timeline')]",
                "//div[contains(@class, 'time-axis')]",
                "//div[contains(@class, 'time-line')]",
                "//div[contains(@class, '时间轴')]",
                "//div[contains(@class, 'time')]",
                "//ul[contains(@class, 'timeline')]",
                "//div[contains(@class, 'ant-timeline')]"
            ]
            
            timeline = None
            for selector in timeline_selectors:
                try:
                    timeline = self.wait.until(EC.presence_of_element_located((By.XPATH, selector)))
                    print(f"✓ 找到时间轴 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if timeline is None:
                print("✗ 未找到时间轴")
                return False
            
            # 高亮显示时间轴
            self.highlight_element(timeline, duration=0.5)
            
            # 查找时间轴上的所有可点击项目
            print("正在查找时间轴项目...")
            timeline_items_selectors = [
                "//div[@id='time']//li[contains(@class, 'TimeLine_tick__245h3')]",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]//li[contains(@class, 'TimeLine_tick__245h3')]",
                "//div[@id='time']//li",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]//li",
                "//div[contains(@class, 'timeline')]//li",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'item')]",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'node')]",
                "//div[contains(@class, 'timeline')]//span",
                "//div[contains(@class, 'timeline')]//button",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'ant-timeline-item')]",
                "//ul[contains(@class, 'timeline')]//li",
                "//div[contains(@class, 'ant-timeline')]//div[contains(@class, 'ant-timeline-item')]"
            ]
            
            timeline_items = []
            for selector in timeline_items_selectors:
                try:
                    items = self.driver.find_elements(By.XPATH, selector)
                    if items:
                        timeline_items = items
                        print(f"✓ 找到 {len(items)} 个时间轴项目 (使用选择器: {selector})")
                        break
                except Exception:
                    continue
            
            if not timeline_items:
                print("✗ 未找到时间轴项目")
                return False
            
            # 依次点击每个时间轴项目
            for i, item in enumerate(timeline_items):
                try:
                    # 获取时间轴项目的文本内容（作为时间标签）
                    date_text = None
                    try:
                        date_text = item.find_element(By.XPATH, ".//span[contains(@class, 'TimeLine_date__aVPu9')]").text
                        print(f"\n📅 点击第 {i+1} 个时间轴项目: {date_text}")
                    except:
                        # 如果找不到date span，尝试获取整个item的文本
                        try:
                            date_text = item.text.strip()
                            if date_text:
                                print(f"\n📅 点击第 {i+1} 个时间轴项目: {date_text}")
                            else:
                                date_text = f"{i+1:02d}"
                                print(f"\n📅 点击第 {i+1} 个时间轴项目...")
                        except:
                            date_text = f"{i+1:02d}"
                            print(f"\n📅 点击第 {i+1} 个时间轴项目...")
                    
                    # 滚动到项目位置
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", item)
                    time.sleep(0.5)
                    
                    # 高亮显示项目
                    self.highlight_element(item, duration=0.1)
                    
                    # 模拟人类鼠标移动
                    self.simulate_human_mouse_movement(item)
                    
                    # 点击项目
                    self.simulate_human_click(item)
                    print(f"✓ 第 {i+1} 个时间轴项目点击完成")
                    
                    # 等待响应
                    time.sleep(1.3)
                    
                    # 截图记录点击后的状态（文件名包含时间信息）
                    self.take_screenshot(f"timeline-{date_text}.jpg")
                    
                    # 等待一下
                    time.sleep(0.2)
                    
                except Exception as e:
                    print(f"✗ 点击第 {i+1} 个时间轴项目失败: {e}")
                    continue
            
            return True
            
        except Exception as e:
            print(f"✗ 处理时间轴失败: {e}")
            return False
    
    def handle_sub_options(self, parent_item, item_index):
        """处理子选项"""
        try:
            # 查找子选项的多种可能选择器
            sub_option_selectors = [
                ".//div[contains(@class, 'ant-tooltip')]//li",
                ".//div[contains(@class, 'ant-dropdown')]//li",
                ".//div[contains(@class, 'ant-menu')]//li",
                ".//div[contains(@class, 'sub')]//li",
                ".//div[contains(@class, 'child')]//li",
                ".//div[contains(@class, 'option')]//li",
                ".//ul[contains(@class, 'sub')]//li",
                ".//ul[contains(@class, 'child')]//li",
                ".//div[contains(@class, 'dropdown')]//li",
                ".//div[contains(@class, 'menu')]//li",
                ".//div[contains(@class, 'list')]//li"
            ]
            
            sub_options = []
            for selector in sub_option_selectors:
                try:
                    options = parent_item.find_elements(By.XPATH, selector)
                    if options:
                        sub_options = options
                        print(f"✓ 找到 {len(options)} 个子选项 (使用选择器: {selector})")
                        break
                except Exception:
                    continue
            
            if not sub_options:
                print("未找到子选项")
                return True
            
            # 依次点击每个子选项
            for j, sub_option in enumerate(sub_options):
                try:
                    print(f"  📋 点击子选项 {j+1}...")
                    
                    # 滚动到子选项位置
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", sub_option)
                    time.sleep(0.3)
                    
                    # 高亮显示子选项
                    self.highlight_element(sub_option, duration=0.5)
                    
                    # 模拟人类鼠标移动
                    self.simulate_human_mouse_movement(sub_option)
                    
                    # 点击子选项
                    self.simulate_human_click(sub_option)
                    print(f"  ✓ 子选项 {j+1} 点击完成")
                    
                    # 等待响应
                    time.sleep(1)
                    
                    # 截图记录子选项点击后的状态
                    self.take_screenshot(f"timeline_item_{item_index:02d}_sub_{j+1:02d}.png")
                    
                except Exception as e:
                    print(f"  ✗ 点击子选项 {j+1} 失败: {e}")
                    continue
            
            return True
            
        except Exception as e:
            print(f"✗ 处理子选项失败: {e}")
            return False
    
    def handle_positioning_popup_with_coords(self, lng, lat, level):
        """处理定位弹窗（使用指定坐标）"""
        try:
            print("正在查找定位弹窗...")
            
            # 等待弹窗出现
            time.sleep(0.5)
            
            # 查找弹窗的多种可能选择器
            popup_selectors = [
                "//div[contains(@class, 'ant-modal')]",
                "//div[contains(@class, 'modal')]",
                "//div[contains(@class, 'popup')]",
                "//div[contains(@class, 'dialog')]",
                "//div[contains(@class, 'positioning')]",
                "//div[contains(@class, '定位')]"
            ]
            
            popup = None
            for selector in popup_selectors:
                try:
                    popup = self.wait.until(EC.presence_of_element_located((By.XPATH, selector)))
                    print(f"✓ 找到定位弹窗 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if popup is None:
                print("✗ 未找到定位弹窗")
                return False
            
            # 高亮显示弹窗
            self.highlight_element(popup, duration=0.5)
            
            # 查找经度输入框
            print("正在查找经度输入框...")
            lng_selectors = [
                "//input[contains(@placeholder, '经度')]",
                "//input[contains(@placeholder, 'lng')]",
                "//input[contains(@placeholder, 'longitude')]",
                "//input[contains(@name, 'lng')]",
                "//input[contains(@id, 'lng')]",
                "//div[contains(@class, 'ant-modal')]//input[1]"
            ]
            
            lng_input = None
            for selector in lng_selectors:
                try:
                    lng_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到经度输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if lng_input:
                # 高亮显示经度输入框
                self.highlight_element(lng_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(lng_input)
                
                # 清空输入框
                lng_input.clear()
                time.sleep(0.2)
                
                # 输入经度
                self.simulate_human_typing(lng_input, str(lng))
                print(f"✓ 经度输入完成: {lng}")
            
            # 查找纬度输入框
            print("正在查找纬度输入框...")
            lat_selectors = [
                "//input[contains(@placeholder, '纬度')]",
                "//input[contains(@placeholder, 'lat')]",
                "//input[contains(@placeholder, 'latitude')]",
                "//input[contains(@name, 'lat')]",
                "//input[contains(@id, 'lat')]",
                "//div[contains(@class, 'ant-modal')]//input[2]"
            ]
            
            lat_input = None
            for selector in lat_selectors:
                try:
                    lat_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到纬度输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if lat_input:
                # 高亮显示纬度输入框
                self.highlight_element(lat_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(lat_input)
                
                # 清空输入框
                lat_input.clear()
                time.sleep(0.2)
                
                # 输入纬度
                self.simulate_human_typing(lat_input, str(lat))
                print(f"✓ 纬度输入完成: {lat}")
            
            # 查找级别输入框
            print("正在查找级别输入框...")
            level_selectors = [
                "//input[contains(@placeholder, '级别')]",
                "//input[contains(@placeholder, 'level')]",
                "//input[contains(@placeholder, 'zoom')]",
                "//input[contains(@name, 'level')]",
                "//input[contains(@id, 'level')]",
                "//div[contains(@class, 'ant-modal')]//input[3]"
            ]
            
            level_input = None
            for selector in level_selectors:
                try:
                    level_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到级别输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if level_input:
                # 高亮显示级别输入框
                self.highlight_element(level_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(level_input)
                
                # 清空输入框
                level_input.clear()
                time.sleep(0.2)
                
                # 输入级别
                self.simulate_human_typing(level_input, str(level))
                print(f"✓ 级别输入完成: {level}")
            
            # 查找查询按钮
            print("正在查找查询按钮...")
            confirm_selectors = [
                "//button[contains(., '查询')]",
                "//button[contains(., '查')]",
                "//button[contains(., '确认')]",
                "//button[contains(., '确定')]",
                "//button[contains(., 'OK')]",
                "//button[contains(., '提交')]",
                "//button[contains(@class, 'ant-btn-primary')]",
                "//div[contains(@class, 'ant-modal')]//button[contains(@class, 'ant-btn-primary')]"
            ]
            
            confirm_button = None
            for selector in confirm_selectors:
                try:
                    confirm_button = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到查询按钮 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if confirm_button:
                # 高亮显示查询按钮
                self.highlight_element(confirm_button, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(confirm_button)
                
                # 点击查询按钮
                self.simulate_human_click(confirm_button)
                print("✓ 查询按钮点击完成")
            
            return True
            
        except Exception as e:
            print(f"✗ 处理定位弹窗失败: {e}")
            return False
    
    def handle_positioning_popup(self):
        """处理定位弹窗"""
        try:
            print("正在查找定位弹窗...")
            
            # 等待弹窗出现
            time.sleep(2)
            
            # 查找弹窗的多种可能选择器
            popup_selectors = [
                "//div[contains(@class, 'ant-modal')]",
                "//div[contains(@class, 'modal')]",
                "//div[contains(@class, 'popup')]",
                "//div[contains(@class, 'dialog')]",
                "//div[contains(@class, 'positioning')]",
                "//div[contains(@class, '定位')]"
            ]
            
            popup = None
            for selector in popup_selectors:
                try:
                    popup = self.wait.until(EC.presence_of_element_located((By.XPATH, selector)))
                    print(f"✓ 找到定位弹窗 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if popup is None:
                print("✗ 未找到定位弹窗")
                return False
            
            # 高亮显示弹窗
            self.highlight_element(popup, duration=0.5)
            
            # 查找经度输入框
            print("正在查找经度输入框...")
            lng_selectors = [
                "//input[contains(@placeholder, '经度')]",
                "//input[contains(@placeholder, 'lng')]",
                "//input[contains(@placeholder, 'longitude')]",
                "//input[contains(@name, 'lng')]",
                "//input[contains(@id, 'lng')]",
                "//div[contains(@class, 'ant-modal')]//input[1]"
            ]
            
            lng_input = None
            for selector in lng_selectors:
                try:
                    lng_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到经度输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if lng_input:
                # 高亮显示经度输入框
                self.highlight_element(lng_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(lng_input)
                
                # 清空输入框
                lng_input.clear()
                time.sleep(0.2)
                
                # 输入经度
                lng_value = "117.65171"  # 默认值
                self.simulate_human_typing(lng_input, lng_value)
                print(f"✓ 经度输入完成: {lng_value}")
            
            # 查找纬度输入框
            print("正在查找纬度输入框...")
            lat_selectors = [
                "//input[contains(@placeholder, '纬度')]",
                "//input[contains(@placeholder, 'lat')]",
                "//input[contains(@placeholder, 'latitude')]",
                "//input[contains(@name, 'lat')]",
                "//input[contains(@id, 'lat')]",
                "//div[contains(@class, 'ant-modal')]//input[2]"
            ]
            
            lat_input = None
            for selector in lat_selectors:
                try:
                    lat_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到纬度输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if lat_input:
                # 高亮显示纬度输入框
                self.highlight_element(lat_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(lat_input)
                
                # 清空输入框
                lat_input.clear()
                time.sleep(0.2)
                
                # 输入纬度
                lat_value = "38.99107"  # 默认值
                self.simulate_human_typing(lat_input, lat_value)
                print(f"✓ 纬度输入完成: {lat_value}")
            
            # 查找级别输入框
            print("正在查找级别输入框...")
            level_selectors = [
                "//input[contains(@placeholder, '级别')]",
                "//input[contains(@placeholder, 'level')]",
                "//input[contains(@placeholder, 'zoom')]",
                "//input[contains(@name, 'level')]",
                "//input[contains(@id, 'level')]",
                "//div[contains(@class, 'ant-modal')]//input[3]"
            ]
            
            level_input = None
            for selector in level_selectors:
                try:
                    level_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到级别输入框 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if level_input:
                # 高亮显示级别输入框
                self.highlight_element(level_input, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(level_input)
                
                # 清空输入框
                level_input.clear()
                time.sleep(0.2)
                
                # 输入级别
                level_value = "17"  # 默认值
                self.simulate_human_typing(level_input, level_value)
                print(f"✓ 级别输入完成: {level_value}")
            
            # 查找查询按钮
            print("正在查找查询按钮...")
            confirm_selectors = [
                "//button[contains(., '查询')]",
                "//button[contains(., '查')]",
                "//button[contains(., '确认')]",
                "//button[contains(., '确定')]",
                "//button[contains(., 'OK')]",
                "//button[contains(., '提交')]",
                "//button[contains(@class, 'ant-btn-primary')]",
                "//div[contains(@class, 'ant-modal')]//button[contains(@class, 'ant-btn-primary')]"
            ]
            
            confirm_button = None
            for selector in confirm_selectors:
                try:
                    confirm_button = self.wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                    print(f"✓ 找到查询按钮 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if confirm_button:
                # 高亮显示查询按钮
                self.highlight_element(confirm_button, duration=0.5)
                
                # 模拟人类鼠标移动
                self.simulate_human_mouse_movement(confirm_button)
                
                # 点击查询按钮
                self.simulate_human_click(confirm_button)
                print("✓ 查询按钮点击完成")
            
            return True
            
        except Exception as e:
            print(f"✗ 处理定位弹窗失败: {e}")
            return False
    
    def get_page_info(self):
        """获取当前页面信息"""
        try:
            title = self.driver.title
            url = self.driver.current_url
            print(f"当前页面标题: {title}")
            print(f"当前页面URL: {url}")
            return title, url
        except Exception as e:
            print(f"✗ 获取页面信息失败: {e}")
            return None, None
    
    def take_screenshot(self, filename=None):
        """截取屏幕截图并保存为JPEG格式"""
        try:
            if filename is None:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"screenshot_{timestamp}.jpg"
            
            # 确保screenshots目录存在
            screenshots_dir = "screenshots"
            if not os.path.exists(screenshots_dir):
                os.makedirs(screenshots_dir)
            
            # 确保文件名以.jpg结尾
            if filename.endswith('.png'):
                filename = filename.replace('.png', '.jpg')
            elif not filename.endswith('.jpg'):
                filename += '.jpg'
            
            # 最终的JPEG文件路径
            final_path = os.path.join(screenshots_dir, filename)
            
            # 先保存为PNG（Selenium默认格式）
            temp_png_path = final_path.replace('.jpg', '_temp.png')
            self.driver.save_screenshot(temp_png_path)
            
            # 使用PIL将PNG转换为JPEG
            from PIL import Image
            try:
                # 打开截图
                img = Image.open(temp_png_path)
                
                # 如果是RGBA模式，转换为RGB
                if img.mode in ('RGBA', 'LA', 'P'):
                    rgb_img = Image.new('RGB', img.size, (255, 255, 255))
                    if img.mode == 'P':
                        img = img.convert('RGBA')
                    rgb_img.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
                    img = rgb_img
                elif img.mode != 'RGB':
                    img = img.convert('RGB')
                
                # 保存为JPEG格式，质量为85%
                img.save(final_path, 'JPEG', quality=85, optimize=True)
                
                # 删除临时PNG文件
                if os.path.exists(temp_png_path):
                    os.remove(temp_png_path)
                
                file_size_kb = os.path.getsize(final_path) / 1024
                print(f"📸 截图已保存: {filename} ({file_size_kb:.1f}KB)")
                
            except Exception as pil_error:
                print(f"⚠️ PIL转换失败: {pil_error}")
                # 如果转换失败，至少保留PNG文件
                if os.path.exists(temp_png_path):
                    os.rename(temp_png_path, final_path.replace('.jpg', '.png'))
                    print(f"📸 截图已保存为PNG: {final_path.replace('.jpg', '.png')}")
                return final_path.replace('.jpg', '.png')
            
            return final_path
            
        except Exception as e:
            print(f"✗ 截图失败: {e}")
            return None
    
    def refresh_page(self):
        """强制刷新整个页面"""
        try:
            if self.driver:
                print("🔄 正在强制刷新整个页面...")
                
                # 方法1: 强制刷新页面
                try:
                    print("方法1: 强制刷新页面...")
                    # 清除所有存储 (已注释)
                    # self.driver.execute_script("""
                    #     // 清除localStorage
                    #     localStorage.clear();
                    #     // 清除sessionStorage
                    #     sessionStorage.clear();
                    #     // 清除cookies
                    #     document.cookie.split(";").forEach(function(c) { 
                    #         document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
                    #     });
                    # """)
                    
                    # 强制刷新页面
                    self.driver.execute_script("window.location.reload(true);")
                    time.sleep(5)  # 增加等待时间
                    print("✓ 方法1: 强制刷新完成")
                    
                except Exception as e1:
                    print(f"方法1失败: {e1}")
                    
                    # 方法2: 尝试点击页面内的刷新按钮
                    try:
                        print("方法2: 尝试点击页面内刷新按钮...")
                        refresh_button_selectors = [
                            "//button[contains(., '刷新')]",
                            "//button[contains(., '重新加载')]",
                            "//button[contains(., '刷新页面')]",
                            "//button[contains(@class, 'refresh')]",
                            "//button[contains(@class, 'reload')]",
                            "//span[contains(@class, 'anticon-reload')]",
                            "//span[contains(@class, 'anticon-refresh')]",
                            "//div[contains(@class, 'refresh')]//button",
                            "//div[contains(@class, 'reload')]//button",
                            "//button[@title='刷新']",
                            "//button[@title='重新加载']",
                            "//*[@id='refresh']",
                            "//*[@id='reload']"
                        ]
                        
                        refresh_button = None
                        for selector in refresh_button_selectors:
                            try:
                                refresh_button = self.driver.find_element(By.XPATH, selector)
                                print(f"✓ 找到刷新按钮: {selector}")
                                break
                            except:
                                continue
                        
                        if refresh_button:
                            # 高亮显示刷新按钮
                            self.highlight_element(refresh_button, duration=0.5)
                            
                            # 模拟人类鼠标移动
                            self.simulate_human_mouse_movement(refresh_button)
                            
                            # 点击刷新按钮
                            self.simulate_human_click(refresh_button)
                            print("✓ 成功点击页面内刷新按钮")
                            time.sleep(5)
                        else:
                            raise Exception("未找到页面内刷新按钮")
                            
                    except Exception as e2:
                        print(f"方法2失败: {e2}")
                        
                        # 方法3: 使用Ctrl+F5强制刷新
                        try:
                            print("方法3: 使用Ctrl+F5强制刷新...")
                            from selenium.webdriver.common.keys import Keys
                            from selenium.webdriver.common.action_chains import ActionChains
                            
                            body = self.driver.find_element(By.TAG_NAME, 'body')
                            actions = ActionChains(self.driver)
                            actions.key_down(Keys.CONTROL).send_keys(Keys.F5).key_up(Keys.CONTROL).perform()
                            time.sleep(5)
                            print("✓ 通过Ctrl+F5强制刷新页面")
                        except Exception as e3:
                            print(f"方法3失败: {e3}")
                            
                            # 方法4: 使用F5键
                            try:
                                print("方法4: 使用F5键刷新...")
                                from selenium.webdriver.common.keys import Keys
                                body = self.driver.find_element(By.TAG_NAME, 'body')
                                body.send_keys(Keys.F5)
                                time.sleep(5)
                                print("✓ 通过F5键刷新页面")
                            except Exception as e4:
                                print(f"方法4失败: {e4}")
                                
                                # 方法5: 使用driver.refresh()
                                try:
                                    print("方法5: 使用driver.refresh()...")
                                    self.driver.refresh()
                                    time.sleep(5)
                                    print("✓ 通过driver.refresh()刷新页面")
                                except Exception as e5:
                                    print(f"方法5失败: {e5}")
                                    
                                    # 方法6: 重新导航到当前URL
                                    try:
                                        print("方法6: 重新导航到当前URL...")
                                        current_url = self.driver.current_url
                                        self.driver.get(current_url)
                                        time.sleep(5)
                                        print("✓ 通过重新导航刷新页面")
                                    except Exception as e6:
                                        print(f"方法6失败: {e6}")
                                        return False
                
                # 等待页面完全加载
                try:
                    print("等待页面完全加载...")
                    # 等待页面body元素出现
                    self.wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
                    
                    # 等待页面完全加载（等待所有资源）
                    self.driver.execute_script("return document.readyState") == "complete"
                    time.sleep(3)  # 额外等待确保页面完全加载
                    
                    print("✓ 页面强制刷新完成")
                    return True
                except TimeoutException:
                    print("⚠️ 页面加载超时，但刷新已执行")
                    return True
                    
        except Exception as e:
            print(f"✗ 页面强制刷新失败: {e}")
            return False
    
    def handle_timeline_with_naming(self, lng, lat, name):
        """处理时间轴点击（使用自定义命名）"""
        try:
            print("正在查找时间轴...")
            
            # 等待时间轴加载
            time.sleep(1)  # 减少等待时间
            
            # 查找时间轴的多种可能选择器
            timeline_selectors = [
                "//div[@id='time']",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]",
                "//div[contains(@class, 'timeline')]",
                "//div[contains(@class, 'time-axis')]",
                "//div[contains(@class, 'time-line')]",
                "//div[contains(@class, '时间轴')]",
                "//div[contains(@class, 'time')]",
                "//ul[contains(@class, 'timeline')]",
                "//div[contains(@class, 'ant-timeline')]"
            ]
            
            timeline = None
            for selector in timeline_selectors:
                try:
                    timeline = self.wait.until(EC.presence_of_element_located((By.XPATH, selector)))
                    print(f"✓ 找到时间轴 (使用选择器: {selector})")
                    break
                except TimeoutException:
                    continue
            
            if timeline is None:
                print("✗ 未找到时间轴")
                return False
            
            # 高亮显示时间轴
            self.highlight_element(timeline, duration=0.5)  # 减少高亮时间
            
            # 查找时间轴上的所有可点击项目
            print("正在查找时间轴项目...")
            timeline_items_selectors = [
                "//div[@id='time']//li[contains(@class, 'TimeLine_tick__245h3')]",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]//li[contains(@class, 'TimeLine_tick__245h3')]",
                "//div[@id='time']//li",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]//li",
                "//div[contains(@class, 'timeline')]//li",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'item')]",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'node')]",
                "//div[contains(@class, 'timeline')]//span",
                "//div[contains(@class, 'timeline')]//button",
                "//div[contains(@class, 'timeline')]//div[contains(@class, 'ant-timeline-item')]",
                "//ul[contains(@class, 'timeline')]//li",
                "//div[contains(@class, 'ant-timeline')]//div[contains(@class, 'ant-timeline-item')]"
            ]
            
            timeline_items = []
            for selector in timeline_items_selectors:
                try:
                    items = self.driver.find_elements(By.XPATH, selector)
                    if items:
                        timeline_items = items
                        print(f"✓ 找到 {len(items)} 个时间轴项目 (使用选择器: {selector})")
                        break
                except Exception:
                    continue
            
            if not timeline_items:
                print("✗ 未找到时间轴项目")
                return False
            
            # 依次点击每个时间轴项目
            for i, item in enumerate(timeline_items):
                try:
                    # 获取时间轴项目的文本内容（作为时间标签）
                    date_text = None
                    try:
                        date_text = item.find_element(By.XPATH, ".//span[contains(@class, 'TimeLine_date__aVPu9')]").text
                        print(f"\n📅 点击第 {i+1} 个时间轴项目: {date_text}")
                    except:
                        # 如果找不到date span，尝试获取整个item的文本
                        try:
                            date_text = item.text.strip()
                            if date_text:
                                print(f"\n📅 点击第 {i+1} 个时间轴项目: {date_text}")
                            else:
                                date_text = f"{i+1:02d}"
                                print(f"\n📅 点击第 {i+1} 个时间轴项目...")
                        except:
                            date_text = f"{i+1:02d}"
                            print(f"\n📅 点击第 {i+1} 个时间轴项目...")
                    
                    # 滚动到项目位置
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", item)
                    time.sleep(0.3)  # 减少等待时间
                    
                    # 高亮显示项目
                    self.highlight_element(item, duration=0.5)  # 减少高亮时间
                    
                    # 模拟人类鼠标移动
                    self.simulate_human_mouse_movement(item)
                    
                    # 点击项目
                    self.simulate_human_click(item)
                    print(f"✓ 第 {i+1} 个时间轴项目点击完成")
                    
                    # 等待响应
                    time.sleep(0.5)  # 减少等待时间
                    
                    # 截图记录点击后的状态（文件名包含时间信息）
                    self.take_screenshot(f"{lng}-{lat}-{name}-{date_text}.jpg")
                    
                    # 等待一下
                    time.sleep(0.5)  # 减少等待时间
                    
                except Exception as e:
                    print(f"✗ 点击第 {i+1} 个时间轴项目失败: {e}")
                    continue
            
            return True
            
        except Exception as e:
            print(f"✗ 处理时间轴失败: {e}")
            return False
    
    def handle_sub_options_with_naming(self, parent_item, item_index, lng, lat, name):
        """处理子选项（使用自定义命名）"""
        try:
            # 等待一下，让子选项有时间出现
            time.sleep(1)
            
            # 查找子选项的多种可能选择器
            sub_option_selectors = [
                # 查找页面上的下拉菜单
                "//div[contains(@class, 'ant-dropdown')]//li",
                "//div[contains(@class, 'ant-menu')]//li",
                "//div[contains(@class, 'ant-tooltip')]//li",
                # 查找时间轴相关的子选项
                "//div[@id='time']//div[contains(@class, 'dropdown')]//li",
                "//div[contains(@class, 'TimeLine_time__kL5a7')]//div[contains(@class, 'dropdown')]//li",
                # 通用子选项选择器
                ".//div[contains(@class, 'sub')]//li",
                ".//div[contains(@class, 'child')]//li",
                ".//div[contains(@class, 'option')]//li",
                ".//ul[contains(@class, 'sub')]//li",
                ".//ul[contains(@class, 'child')]//li",
                ".//div[contains(@class, 'dropdown')]//li",
                ".//div[contains(@class, 'menu')]//li",
                ".//div[contains(@class, 'list')]//li"
            ]
            
            sub_options = []
            for selector in sub_option_selectors:
                try:
                    # 先在整个页面查找
                    options = self.driver.find_elements(By.XPATH, selector)
                    if options:
                        sub_options = options
                        print(f"✓ 找到 {len(options)} 个子选项 (使用选择器: {selector})")
                        break
                except Exception:
                    continue
            
            # 如果没找到，尝试在父元素内查找
            if not sub_options:
                for selector in sub_option_selectors:
                    try:
                        options = parent_item.find_elements(By.XPATH, selector)
                        if options:
                            sub_options = options
                            print(f"✓ 在父元素内找到 {len(options)} 个子选项 (使用选择器: {selector})")
                            break
                    except Exception:
                        continue
            
            if not sub_options:
                print("未找到子选项")
                return True
            
            # 依次点击每个子选项
            for j, sub_option in enumerate(sub_options):
                try:
                    print(f"  📋 点击子选项 {j+1}...")
                    
                    # 滚动到子选项位置
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", sub_option)
                    time.sleep(0.3)
                    
                    # 高亮显示子选项
                    self.highlight_element(sub_option, duration=0.5)
                    
                    # 模拟人类鼠标移动
                    self.simulate_human_mouse_movement(sub_option)
                    
                    # 点击子选项
                    self.simulate_human_click(sub_option)
                    print(f"  ✓ 子选项 {j+1} 点击完成")
                    
                    # 等待响应
                    time.sleep(1)
                    
                    # 截图记录子选项点击后的状态（使用自定义命名）
                    self.take_screenshot(f"{lng}-{lat}-{name}-timeline_item_{item_index:02d}_sub_{j+1:02d}.png")
                    
                except Exception as e:
                    print(f"  ✗ 点击子选项 {j+1} 失败: {e}")
                    continue
            
            return True
            
        except Exception as e:
            print(f"✗ 处理子选项失败: {e}")
            return False
    
    def close_browser(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            print("✓ 浏览器已关闭")

def main():
    """主函数"""
    automation = BrowserAutomation()
    
    try:
        print("=== 浏览器自动化脚本 ===")
        print("1. 初始化浏览器驱动")
        
        # 自动选择连接方式：优先连接现有浏览器
        print("正在尝试连接到现有浏览器...")
        if not automation.connect_to_existing_browser():
            print("连接失败，启动新浏览器实例...")
            if not automation.setup_driver():
                return
        
        # 获取页面信息
        automation.get_page_info()
        
        # 等待页面加载
        print("等待页面完全加载...")
        time.sleep(3)
        
        # 截取初始截图
        print("\n📸 截取初始页面截图")
        # automation.take_screenshot("01_initial_page.png")
        
        # 执行自动化操作
        print("\n2. 开始自动化操作")
        
        # 点击定位按钮
        print("\n🔍 步骤1: 点击定位按钮")
        if automation.find_and_click_positioning_button():
            print("✓ 定位按钮点击成功")
            # 截图记录点击后的状态
            # automation.take_screenshot("02_after_positioning_click.png")
        else:
            print("✗ 定位按钮点击失败")
        
        # 等待一下
        time.sleep(2)
        
        # 处理弹出的定位窗口
        print("\n📍 步骤2: 处理定位弹窗")
        if automation.handle_positioning_popup():
            print("✓ 定位弹窗处理成功")
            # 截图记录弹窗处理后的状态
            # automation.take_screenshot("03_after_popup_input.png")
        else:
            print("✗ 定位弹窗处理失败")
        
        # 等待一下
        time.sleep(2)
        
        # 处理时间轴
        print("\n⏰ 步骤3: 处理时间轴")
        if automation.handle_timeline():
            print("✓ 时间轴处理成功")
            # 截图记录时间轴处理后的状态
            # automation.take_screenshot("04_after_timeline.png")
        else:
            print("✗ 时间轴处理失败")
        
        # 等待一下
        time.sleep(2)
        
        # 最终截图
        print("\n📸 截取最终结果截图")
        # automation.take_screenshot("05_final_result.png")
        
        print("\n✅ 自动化操作完成！")
        print("📁 所有截图已保存到 screenshots/ 目录")
        
    except KeyboardInterrupt:
        print("\n用户中断操作")
    except Exception as e:
        print(f"\n✗ 程序执行出错: {e}")
        # 出错时也截图
        # automation.take_screenshot("error_screenshot.png")
    finally:
        automation.close_browser()

if __name__ == "__main__":
    main()
